package com.moonstar.controller;
import com.moonstar.pojo.Result;
import com.moonstar.pojo.User;
import com.moonstar.service.UserService;
import com.moonstar.utils.PageUtils;
import com.moonstar.utils.Query;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/user")
@CrossOrigin
public class UserController {

    @Autowired
    private UserService userService;

    @CrossOrigin
    @GetMapping("/login")
    public Result login(@RequestParam("username") String username, @RequestParam("password") String password,
                        HttpSession session) {
        User param = new User();
        param.setUsername(username);
        param.setPassword(password);
        User user = userService.login(param);
        if(user==null){
            return Result.error("用户名或密码错误");
        }else{
            session.setAttribute("loginUser", user);
            return Result.success();
        }
    }


    //添加用户
    @PostMapping("/save")
    public Result save(User user){
        HashMap<String, Object> map = new HashMap<>();
        map.put("username", user.getUsername());
        List<User> list = userService.list(map);
        if(!list.isEmpty()){
            return Result.error("用户名已存在");
        }
        user.setRole(1);// 1 普通用户
        userService.save(user);
        return Result.success();
    }

//    //删除用户
//    @DeleteMapping("/del/{id}")
//    public Result delete(@PathVariable Long id){
//        userService.remove(id);
//        return Result.success(null);
//    }
//
//    //更改用户信息
//    @PostMapping("/update")
//    public Result update(@RequestBody User user){
//        userService.update(user);
//        return Result.success(null);
//    }
    //查询用户列表
    @GetMapping("/list")
    public PageUtils list(@RequestParam Map<String, Object> params) {
        // 查询列表数据
        Query query = new Query(params);
        List<User> userList = userService.list(query);
        int total = userService.count(query);
        PageUtils pageUtils = new PageUtils(userList, total);
        return pageUtils;
    }

    @GetMapping("/findAll")
    public Result<List<User>> findAll(){
        List<User> list = userService.list(new HashMap<>());
        return Result.success(list);
    }

    @GetMapping("/getUsername/{id}")
    public String getUsername(@PathVariable Long id) {
        try {
            User user1 = userService.get(id);
            if(user1 != null){
                return user1.getUsername();
            }else {
                User user = userService.get(id);
                return user.getUsername();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}
